<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>event</title>
</head>
<body>
<canvas>
</canvas>
<script>
  var cvs = document.querySelector("canvas"),
      ctx = cvs.getContext('2d'),
      circles = [];

  addCircle();
  draw();
  function addCircle() {
    var w = cvs.width,
        h = cvs.height,
        i;
    for(i = 0; i < 2; i++) {
      var circle = {};
      circle.x = w * Math.random();
      circle.y = h * Math.random();
      circles.push(circle);
    }
  }

  function draw() {
    var i;
    for(i=0; i < circles.length; i++) {
      drawCircle(circles[i]);
    }
  }

  function drawCircle(circle) {
    ctx.beginPath();
    ctx.arc(circle.x, circle.y, 10, 0, 2*Math.PI, false);
    ctx.closePath();
    ctx.stroke();
    ctx.fillStyle = 'blue';
    ctx.fill()
  }

  function onclick() {
    var position = cvs.getBoundingClientRect(),
        canvasX = event.x - position.left, //得到相对于canvas的坐标x
        canvasY = event.y - position.top;  //得到相对于canvas的坐标y
    reDraw(canvasX,canvasY);
  }

  function reDraw(x, y) {
    var i;
    for(i=0; i < circles.length; i++) {
      drawCircle(circles[i]);
      if(ctx.isPointInPath(x,y)) {  //判断是否在路径内
        ctx.fillStyle = "#f00";
        ctx.fill();
      }
    }
  }

  window.addEventListener('click', onclick, false);
</script>
</body>
</html>
